package com.zhanghaijun.util;

import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

/**
 * Created by zhanghaijun on 15/7/28.
 */
public class EhcacheUtil {
    private static CacheManager cacheManager = getCacheManager();

    public  static CacheManager getCacheManager() {
        try {
            net.sf.ehcache.CacheManager ehcacheCacheManager
                    = new net.sf.ehcache.CacheManager(new ClassPathResource("ehcache.xml").getInputStream());
            return ehcacheCacheManager;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static Object get(String cacheName, Object key) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache != null) {
            Element element = cache.get(key);
            if (element != null) {
                return element.getObjectValue();
            }
        }
        return null;
    }

    /**
     * 不设置缓存过期时间 则走配置的失效时间
     * @param cacheName
     * @param key
     * @param value
     */
    public static void put(String cacheName, Object key, Object value) {
        Ehcache cache = cacheManager.getCache(cacheName);
        if (cache != null) {
            cache.put(new Element(key, value));
        }
    }


    /**
     * 设置了缓存时间 则走缓存的时间
     * @param cacheName
     * @param key
     * @param value
     * @param exp
     */
    public static void put(String cacheName, Object key, Object value,int exp) {
        Ehcache cache = cacheManager.getCache(cacheName);
        if (cache != null) {
            Element element = new Element(key, value,false,0,exp);
            cache.put(element);
        }
    }

    public static boolean remove(String cacheName, Object key) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache != null) {
            return cache.remove(key);
        }
        return false;
    }
}
